import React, { useState } from 'react'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import Input from '@/components/Input'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { login, sendCode } from '@/store/actions/login'
import { Toast } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router'

export default function Login() {
  const history = useHistory()
  const dispatch = useDispatch()
  const location = useLocation()
  const [count, setCount] = useState(0)
  const form = useFormik({
    // 表单的初始值
    initialValues: {
      mobile: '13911111111',
      code: '246810',
    },

    validationSchema: Yup.object({
      mobile: Yup.string()
        .required('必填')
        .matches(/^1[3-9]\d{9}$/, '填写正确的手机号'),
      code: Yup.string()
        .required('必填')
        .matches(/^\d{6}$/, '填写 6 位数字验证码'),
    }),
    onSubmit: async (vals) => {
      try {
        await dispatch(login(vals))
        Toast.success('登录成功!')
        const pathname = location?.state?.pathname || '/home'
        history.replace(pathname)
      } catch (err) {
        console.dir(err)
      }
    },
  })
  const { mobile, code } = form.values
  // 发送验证码
  const onSendCode = async () => {
    if (count === 0) {
      if (/^1[3-9]\d{9}$/.test(mobile)) {
        try {
          await dispatch(sendCode(mobile))
          Toast.success('已发送！')

          setCount(60)
          let countTimer = setInterval(() => {
            setCount((prveCount) => {
              if (prveCount === 1) {
                clearInterval(countTimer)
              }
              return prveCount - 1
            })
          }, 1000)
        } catch (err) {
          console.log(err)
        }
      }
    }
  }
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={form.handleSubmit}>
          {/* 手机号输入框 */}
          <div className="input-item">
            <Input
              value={mobile}
              onChange={form.handleChange}
              onBlur={form.handleBlur}
              placeholder="请输入手机号"
              name="mobile"
              maxLength="11"
            ></Input>
            {form.touched.mobile && form.errors.mobile && (
              <div className="validate">{form.errors.mobile}</div>
            )}
          </div>
          {/* 短信验证码输入框 */}
          <div className="input-item">
            <Input
              value={code}
              onChange={form.handleChange}
              onBlur={form.handleBlur}
              placeholder="请输入验证码"
              name="code"
              extra={count > 0 ? count : '获取验证码'}
              onExtraClick={onSendCode}
              maxLength="6"
            ></Input>
            {form.touched.code && form.errors.code && (
              <div className="validate">{form.errors.code}</div>
            )}
          </div>

          {/* 登录按钮 */}
          <button
            disabled={!form.isValid}
            type="submit"
            className={classNames([
              'login-btn',
              form.isValid ? '' : 'disabled',
            ])}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
